import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { TagServiceProxy, ArticleDto, TagDto, CreateArticleInput, ArticleServiceProxy } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import { OrganizationUnitsTreeComponent, IOrganizationUnitsTreeComponentData } from '../shared/organization-unit-tree.component';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    selector: 'createOrEditArticleModal',
    templateUrl: './create-or-edit-article-modal.component.html',
    styles: []
})
export class CreateOrEditArticleModalComponent extends AppComponentBase {

    @ViewChild('nameInput') nameInput: ElementRef;
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;       //
    // canChangeUserName = true;
    // isTwoFactorEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled');
    // isLockoutEnabled: boolean = this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled');

    article: ArticleDto;
    tags: TagDto[];
    choosedTags: TagDto[];

    constructor(
        injector: Injector,
        private _articleService: ArticleServiceProxy,
        private _tagService: TagServiceProxy
    ) {
        super(injector);
        this.getTags();
    }

    getTags(): void {
        this._tagService.getTags().subscribe(result => {
            this.tags = new Array<TagDto>();
            result.items.forEach(item => {
                if (item.tagType === 1) {
                    this.tags.push(item);
                }
            });
        });
    }

    chooseTag(tag: TagDto): void {
        if (this.choosedTags.indexOf(tag) === -1) {
            this.choosedTags.push(tag);
        } else {
            abp.notify.error('已经选着过这个标签！');
        }
    }
    removeTag(tag: TagDto): void {
        if (this.choosedTags.indexOf(tag) !== -1) {
            this.choosedTags.splice(this.choosedTags.indexOf(tag), 1);
        } else {
            abp.notify.warn('这儿有错误');
        }
    }

    show(articleId?: number): void {
        this.article = new ArticleDto();
        this.choosedTags = new Array<TagDto>();
        if (!articleId) {
            this.active = true;
            this.modal.show();
        } else {
            this._articleService.get(articleId).subscribe(Result => {
                this.article = Result;
                if (Result.tagIds) {
                    let tId = Result.tagIds.split(',');
                    tId.forEach(result => {
                        this.tags.forEach(item => {
                            if (item.id.toString() === result) {
                                this.choosedTags.push(item);
                            }
                        });
                    });
                }

                this.modal.show();
            });
        }

    }


    onShown(): void {
        this.active = true;
        // $(this.nameInput.nativeElement).focus();

        // this.organizationUnitTree.data = <IOrganizationUnitsTreeComponentData>{
        //     allOrganizationUnits: this.allOrganizationUnits,
        //     selectedOrganizationUnits: this.memberedOrganizationUnits
        // };
    }

    save(): void {
        let input = new CreateArticleInput();

        input.title = this.article.title;
        input.content = this.article.content;
        input.id = this.article.id === undefined || this.article.id === 0 ? 0 : this.article.id;
        input.publishRemark = this.article.publishRemark;
        input.creatorUserName = this.appSession.user.name;
        if (this.article.publishRemark) {
            input.publishedTime = moment(moment().format('YYYY-MM-DD HH:mm:ssZ'));
        }
        input.tagIds = '';
        this.choosedTags.forEach(item => { input.tagIds += item.id.toString() + ','; });
        this.saving = true;
        if (input.id === 0) {
            this._articleService.create(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        } else {
            this._articleService.update(input)
                .finally(() => { this.saving = false; })
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close();
                    this.modalSave.emit(null);
                });
        }
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}


